#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import sys
import os
ProjectPath = os.path.dirname(os.getcwd())
sys.path.insert(0, ProjectPath)
sys.path.insert(0, os.path.join(ProjectPath, 'common'))
sys.path.insert(0, os.path.join(ProjectPath, 'database'))

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import logging
logging.getLogger().setLevel(logging.DEBUG)

import databasefunction
import commonfunction
import friend.frienddatabase as frienddatabase


PAGE_SIZE = 20

class CFriendPage(commonfunction.CBasePage):
    def get(self):
        TemplateValues = self.GetDefaultTemplateValue()
        LoginName = commonfunction.GetUserLoginName()
        TimeDelta = self.GetTheSessionTimeDelta()

        Tag = self.request.get('tag', '').encode('UTF-8')
        ShowUserKeyStr = self.request.get('user', '').encode('UTF-8')
        CurPage = self.request.get('page', '').encode('UTF-8')
        CurCommentOnPage = self.request.get('commentonpage', '').encode('UTF-8')
        TemplateValues.update( { 'Tag':Tag, } )

        ShowUserName = ''
        if Tag == 'my':
            ShowUserName = LoginName
        elif Tag == 'user':
            ShowUser = databasefunction.GetOneTableItem('CUserTable', ShowUserKeyStr)
            if ShowUser:
                ShowUserName = ShowUser.LoginName

        #添加朋友显示内容
        Friends, PrePage, NextPage = frienddatabase.GetOneUserFriendRecord(ShowUserName, 1, PAGE_SIZE, TimeDelta, CurPage)
#	self.response.out.write( "ShowUserName : %s, Friends = %s" % (ShowUserName, Friends) )
        TemplateValues.update( { 'Friends':Friends, 'PrePage':PrePage, 'NextPage':NextPage, } )
        #重置当前页面
        NewCurPage = CurPage
        if Friends:
            NewCurPage = Friends[0].Date
        TemplateValues.update( { 'CurPage':NewCurPage, } )

        AcceptFriends = None
        WaitFriends = None
        #添加本用户显示内容
        if 0 < len(LoginName) and Tag == 'my':
            AcceptFriends = frienddatabase.GetApplyMyFriendRecord(TimeDelta)
            WaitFriends, WaitPrePage, WaitNextPage = frienddatabase.GetOneUserFriendRecord(ShowUserName, 0, 1000, TimeDelta)
            RefuseFriends, RefusePrePage, RefuseNextPage = frienddatabase.GetOneUserFriendRecord(ShowUserName, 2, 1000, TimeDelta)
            TemplateValues.update( { 'AcceptFriends':AcceptFriends, 'WaitFriends':WaitFriends, 'RefuseFriends':RefuseFriends, } )

        
        TemplateFilePath = self.GetRightLanguageHtmlFilePath('friend')

#	self.response.out.write("TemplateValues : %s" % TemplateValues)
	self.response.out.write(template.render(TemplateFilePath, TemplateValues))

    def head(self):
        pass



class CFriendAddPage(commonfunction.CBasePage):
    def post(self):
        UserKeyStr = self.request.get('item', '')
        ApplyExplain = self.request.get('explain', '').rstrip()
        UserInfo = databasefunction.GetOneTableItem('CUserTable', UserKeyStr)

        CanAdd = True
        if UserInfo == None:
            CanAdd = False
            if self.GetTheSessionLanguage() == 'zh-cn':
                TemplateValues.update( { 'Error':u'该用户不存在', } )
            else:
                TemplateValues.update( { 'Error':u'The user is not exist.', } )
        else:
            if UserInfo.AllowFriend == 2:
                CanAdd = False
                if self.GetTheSessionLanguage() == 'zh-cn':
                    TemplateValues.update( { 'Error':u'该用户不允许别人加为好友', } )
                else:
                    TemplateValues.update( { 'Error':u'The user is not allow anybody become his friend.', } )

        if CanAdd:
            frienddatabase.AddFriend(UserInfo.LoginName, UserInfo.AllowFriend, ApplyExplain)
            self.redirect('/friend?tag=my')
        else:
            TemplateValues.update( { 'BackUrl':'/', } )
            TemplateFilePath = self.GetRightLanguageHtmlFilePath('error')
            self.response.out.write(template.render(TemplateFilePath, TemplateValues))
            


class CFriendResponsionPage(commonfunction.CBasePage):
    def post(self):
        LoginName = commonfunction.GetUserLoginName()
        if 0 < len(LoginName):
            ResponsionState = int(self.request.get('responsion', '1'))
            AcceptItems = self.request.get('acceptitem', allow_multiple=True)

            ItemLoginName = ''
            for OneFriendName in AcceptItems:
                ItemLoginName = databasefunction.GetOneUserLoginNameFromLoginOrNickName(OneFriendName, False)
                frienddatabase.AcceptOneFriend(ItemLoginName, ResponsionState)
            
        self.redirect('/friend?tag=my')


class CFriendDeletePage(commonfunction.CBasePage):
    def post(self):
        ResponsionState = int(self.request.get('responsion', '-1'))
        LoginName = commonfunction.GetUserLoginName()
        if 0 < len(LoginName):
            AcceptItems = self.request.get('deleteitem', allow_multiple=True)

            ItemLoginName = ''
            for OneFriendName in AcceptItems:
                ItemLoginName = databasefunction.GetOneUserLoginNameFromLoginOrNickName(OneFriendName, False)
                frienddatabase.DeleteOneFriend(ItemLoginName, ResponsionState)

        self.redirect('/friend?tag=my')






def main():
    application = webapp.WSGIApplication([
                                            ('/friend', CFriendPage),
                                            ('/friend_add', CFriendAddPage),
                                            ('/friend_responsion', CFriendResponsionPage),
                                            ('/friend_delete', CFriendDeletePage),
                                         ], debug=True)
    
    wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
    main()


